package com.sparrow.rpc.manager;

import com.ecwid.consul.v1.health.model.HealthService;
import com.sparrow.common.util.PropertiesUtil;
import com.sparrow.rpc.domain.RpcNode;
import com.sparrow.rpc.socket.msg.req.RpcLoginRequest;
import com.sparrow.rpc.socket.msg.resp.RpcLoginResponse;
import com.sparrow.rpc.socket.session.RpcSession;
import com.sparrow.servicemgr.consul.ConsulManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 分布式consul rpc 节点管理
 */
public class DistributeConsulRpcNodeManager extends AbsRpcNodeManager{
    private static final Logger logger = LoggerFactory.getLogger(DistributeConsulRpcNodeManager.class);

    @Autowired
    ConsulManager consulManager;

    @PostConstruct
    private void init() {
        //注册自己
        self = registerNode(PropertiesUtil.getProperty("rpc.node.id"), PropertiesUtil.getProperty("rpc.node.ip"), PropertiesUtil.getPropertyAsInt("rpc.node.port"));
    }

    @Override
    public RpcNode getNode(String id) {
        if (!nodeMap.containsKey(id)) {
            refresh("game");
        }
        return nodeMap.get(id);
    }

    @Override
    public void onRpcNodeLogin(RpcSession session, RpcLoginRequest nodeRequest) {

    }

    @Override
    public void onRpcNodeLoginResp(RpcSession session, RpcLoginResponse response) {

    }

    public void refresh(String serviceName) {
        logger.info("刷新consul节点");
        List<HealthService> services = consulManager.getHealthServices(serviceName);
        for (HealthService hs : services) {
            String id = hs.getService().getId();
            String address = hs.getService().getAddress();
            int port = hs.getService().getPort();
            registerNode(id, address, port);
        }
    }

}
